//
//  PayWayViewController.m
//  MeterMart
//
//  Created by ENERGY on 2018/9/22.
//  Copyright © 2018年 ENERGY. All rights reserved.
//

#import "PayWayViewController.h"
#import <AlipaySDK/AlipaySDK.h>
#import "APAuthInfo.h"
#import "APOrderInfo.h"
#import "APRSASigner.h"
#import "AlipayCustom.h"
#import "ConfirmComboViewController.h"
#import "WeChatLoginViewController.h"
#import "MallViewController.h"
@interface PayWayViewController ()
@property (nonatomic, strong)UIViewController * lastVC;//push过来的控制器
@property (nonatomic, strong)UIViewController * rootVC;//根控制器
@property (nonatomic, strong)UILabel * alertLab;//提示信息
@property (nonatomic, strong)UIButton * wechatBtn;
@property (nonatomic, strong)UIButton * wechatCoverBtn;//
@property (nonatomic, strong)UIButton * alipayBtn;
@property (nonatomic, strong)UIButton * alipayCoverBtn;//
@property (nonatomic, strong)UIButton * appSelfBtn;//一米账户支付
@property (nonatomic, strong)UIButton * appSelfCoverBtn;
@property (nonatomic, assign)int payWay;//1、微信支付  2、支付宝支付
@property (nonatomic, strong)UILabel * instructionLab;//说明
@property (nonatomic, strong)NSString * totalMoney;//总金额
@property (nonatomic, strong)NSString * tokenString;//
@property (nonatomic, strong)NSString * phoneString;//

- (void)weiXinpay:(NSDictionary *)dic;//微信支付
- (void)alipayWay:(NSString * )codeString;//阿里支付
- (void)appSelfCoverBtnClick;
- (void)alipayCoverBtnClick;
- (void)wechatCoverBtnClick;
- (void)ifLogin;
@end

@implementation PayWayViewController(networkin)
//酒店和其他进
- (void)hotelAndOtherSubmitOrder{
    NSDictionary * dic = @{
                           @"ordernum":self.listID,
                           @"token":self.tokenString,
                           @"phone":self.phoneString,
                           };
    [self showprogressHUD];
    [[AFAppDotNetAPIClient sharedClient] POST:@"orderiosApi/submitOrder_hotel" parameters:dic progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [self hiddenProgressHUD];
        if ([responseObject[@"sign"] isEqualToString:@"1"]) {
            self.totalMoney = responseObject[@"list"][@"totalmoney"];
            self.alertLab.text = [NSString stringWithFormat:@"金额%@元", self.totalMoney];
            if ([responseObject[@"list"][@"must"] isEqualToString:@"1"]) {
//                self.payWay = 3;
                [self appSelfCoverBtnClick];
                self.instructionLab.hidden = YES;
                self.instructionLab.text = @"*只可余额支付";
                self.instructionLab.hidden = NO;
                self.wechatCoverBtn.userInteractionEnabled = NO;
                self.alipayCoverBtn.userInteractionEnabled = NO;
            }else if ([responseObject[@"list"][@"must"] isEqualToString:@"0"] && [responseObject[@"list"][@"may"] isEqualToString:@"0"]){
//                self.payWay = 1;
                [self wechatCoverBtnClick];
                self.instructionLab.hidden = YES;
                self.instructionLab.text = @"*余额不足";
                self.instructionLab.hidden = NO;
                self.appSelfCoverBtn.userInteractionEnabled = NO;
            }else{
                self.instructionLab.hidden = NO;
            }
        }else if ([[NSString stringWithFormat:@"%@", responseObject[@"sign"]] isEqualToString:@"400"]) {
            [self ifLogin];
        }else{
            ShowMessage(responseObject[@"msg"]);
            int64_t delayInSeconds = 0.5;// 延迟的时间
            /*
             *@parameter 1,时间参照，从此刻开始计时
             *@parameter 2,延时多久，此处为秒级，还有纳秒等。10ull * NSEC_PER_MSEC
             */
            dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
            dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
                [self.navigationController popViewControllerAnimated:YES];
            });
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [self showError:error];
        [self hiddenProgressHUD];
    }];
}
//首饰进
- (void)jewelrySubmitOrder{
    NSDictionary * dic = @{
                           @"token":self.tokenString,
                           @"phone":self.phoneString,
                           @"remarks":self.remarks,
                           @"ordernum":self.listID,
                           @"addressid":self.addressID
                           };
    [self showprogressHUD];
    [[AFAppDotNetAPIClient sharedClient] POST:@"orderiosApi/submitOrder" parameters:dic progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [self hiddenProgressHUD];
        if ([[NSString stringWithFormat:@"%@", responseObject[@"sign"]] isEqualToString:@"1"]) {
            self.totalMoney = responseObject[@"list"][@"totalmoney"];
            self.alertLab.text = [NSString stringWithFormat:@"金额%@元", self.totalMoney];
            if ([responseObject[@"list"][@"must"] isEqualToString:@"1"]) {
                [self appSelfCoverBtnClick];
                self.instructionLab.hidden = YES;
                self.instructionLab.text = @"*只可余额支付";
                self.instructionLab.hidden = NO;
                self.wechatCoverBtn.userInteractionEnabled = NO;
                self.alipayCoverBtn.userInteractionEnabled = NO;
            }else if ([responseObject[@"list"][@"must"] isEqualToString:@"0"] && [responseObject[@"list"][@"may"] isEqualToString:@"0"]){
                [self wechatCoverBtnClick];
                self.instructionLab.hidden = YES;
                self.instructionLab.text = @"*余额不足";
                self.instructionLab.hidden = NO;
                self.appSelfCoverBtn.userInteractionEnabled = NO;
            }else{
                self.instructionLab.hidden = NO;
            }
        }else if ([[NSString stringWithFormat:@"%@", responseObject[@"sign"]] isEqualToString:@"400"]) {
            [self ifLogin];
        }else{
            ShowMessage(responseObject[@"msg"]);
            int64_t delayInSeconds = 0.5;// 延迟的时间
            /*
             *@parameter 1,时间参照，从此刻开始计时
             *@parameter 2,延时多久，此处为秒级，还有纳秒等。10ull * NSEC_PER_MSEC
             */
            dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
            dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
                [self.navigationController popViewControllerAnimated:YES];
            });
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [self showError:error];
        [self hiddenProgressHUD];
        int64_t delayInSeconds = 0.5;// 延迟的时间
        dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
        dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
            [self.navigationController popViewControllerAnimated:YES];
        });
    }];
}
//微信支付
- (void)weChatPay{
    [self showprogressHUD];
    NSDictionary * dic = @{
                           @"ordernum":self.listID,
                           @"phone":self.phoneString,
                           @"token":self.tokenString
                           };
    [[AFAppDotNetAPIClient sharedClient] POST:@"authiosApi/payorder" parameters:dic progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [self hiddenProgressHUD];
        if ([responseObject[@"sign"] isEqualToString:@"1"]) {
            [self weiXinpay:responseObject[@"list"]];
        }else if ([[NSString stringWithFormat:@"%@", responseObject[@"sign"]] isEqualToString:@"400"]) {
            [self ifLogin];
        }else{
            ShowMessage(responseObject[@"msg"]);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [self showError:error];
        [self hiddenProgressHUD];
    }];
}
//阿里支付
- (void)aliPay{
    NSDictionary * dic = @{
                           @"body":self.produceTitle,
                           @"subject":self.produceDescribe,
                           @"out_trade_no":self.listID,
                           @"total_amount":self.totalMoney
                           };
    [self showprogressHUD];
    [[AFAppDotNetAPIClient sharedClient] POST:@"usiosApi/alipay" parameters:dic progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [self hiddenProgressHUD];
        if ([[NSString stringWithFormat:@"%@", responseObject[@"sign"]] isEqualToString:@"1"]) {
            [self alipayWay:responseObject[@"list"]];
        }else if ([[NSString stringWithFormat:@"%@", responseObject[@"sign"]] isEqualToString:@"400"]) {
            [self ifLogin];
        }else{
            ShowMessage(responseObject[@"msg"]);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [self hiddenProgressHUD];
        [self showError:error];
    }];
}
//一米支付
- (void)appSelfAccountPay{
    NSDictionary * dic = @{
                           @"phone":self.phoneString,
                           @"token":self.tokenString,
                           @"ordernum":self.listID
                           };
    [self showprogressHUD];
    [[AFAppDotNetAPIClient sharedClient] POST:@"orderiosApi/yuepay" parameters:dic progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [self hiddenProgressHUD];
        if ([responseObject[@"sign"] isEqualToString:@"1"]) {
            [[NSNotificationCenter defaultCenter]postNotificationName:@"payStatus" object:nil userInfo:@{@"payStatus":@"1"}];
            int64_t delayInSeconds = 1.0; // 延迟的时间
            /*
             *  delta:
             *
             *  @parameter 1.时间参照，从此刻开始计时
             *  @parameter 2.延时多久，此处为秒级，还有纳秒等: 10ull * NSEC_PER_MSEC
             */
            ShowMessage(@"支付成功");
            __weak typeof(self)weakSelf = self;
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [weakSelf.tabBarController setSelectedIndex:2];
                [weakSelf.navigationController popToRootViewControllerAnimated:YES];
            });
        }else if ([[NSString stringWithFormat:@"%@", responseObject[@"sign"]] isEqualToString:@"400"]) {
            [self ifLogin];
        }else{
            ShowMessage(responseObject[@"msg"]);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [self hiddenProgressHUD];
        [self showError:error];
    }];
}
@end

@implementation PayWayViewController
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationItem.title = @"请选择支付方式";
    
    if ([[UserModel sharedInstanced].token isEqualToString:@""] || [UserModel sharedInstanced].token == nil || [[UserModel sharedInstanced].token length] == 0 || [[UserModel sharedInstanced].mobile isEqualToString:@""] || [UserModel sharedInstanced].mobile == nil || [[UserModel sharedInstanced].mobile length] == 0) {
        self.tokenString = @"";
        self.phoneString = @"";
    }else{
        self.tokenString = [UserModel sharedInstanced].token;
        self.phoneString = [UserModel sharedInstanced].mobile;
    }
    
    NSArray *vcsArray = [self.navigationController viewControllers];
    NSInteger vcCount = vcsArray.count;
    self.lastVC = vcsArray[vcCount-2];
    if ([self.lastVC isKindOfClass:[ConfirmComboViewController class]]) {
        //网络接口，从酒店和其他进
        [self hotelAndOtherSubmitOrder];
    }else{
        [self jewelrySubmitOrder];
    }
    if (self.produceTitle == nil || [self.produceTitle isEqualToString:@""] || [self.produceTitle length] == 0) {
        self.produceTitle = @"";
    }
    if (self.produceDescribe == nil || [self.produceTitle isEqualToString:@""] || [self.produceDescribe length] == 0) {
        self.produceDescribe = @"";
    }
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(aliPaySucceed:)
                                                 name:ZLAliReturnSucceedPayNotification
                                               object:nil];//支付成功
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(aliPayFailed:)
                                                 name:ZLAliReturnFailedPayNotification
                                               object:nil];//支付失败
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(weixinPaySuccess:) name:WeChatReturnSucceedPayNotification object:nil];//微信支付
    
}
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self setUpViews];//添加控件
}

- (void)setUpViews{
    UIView * topLineView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 1)];
    topLineView.backgroundColor = getColor(grayColor);
    [self.view addSubview:topLineView];
    //提示信息
    self.alertLab = [[UILabel alloc] initWithFrame:CGRectMake(0, topLineView.bottom, SCREEN_WIDTH, 58/WIDTH_6_SCALE)];
    [self label:self.alertLab withFont:DEF_FontSize_14 withText:[NSString stringWithFormat:@"金额%@元", self.totalMoney] withTextColor:[UIColor blackColor] withTextAlignment:NSTextAlignmentCenter withView:self.view];
    self.alertLab.numberOfLines = 0;
    self.alertLab.lineBreakMode = 0;
    //微信图标
    UIImageView * wechatImg = [[UIImageView alloc] initWithFrame:CGRectMake(20/WIDTH_6_SCALE, self.alertLab.bottom + 20/WIDTH_6_SCALE, 30/WIDTH_6_SCALE, 28/WIDTH_6_SCALE)];
    wechatImg.image = [UIImage imageNamed:@"weChatPay"];
    [self.view addSubview:wechatImg];
    //微信标题
    UILabel * wechatLab = [[UILabel alloc] initWithFrame:CGRectMake(wechatImg.right + 12/WIDTH_6_SCALE, 0, 100/WIDTH_6_SCALE, 15/WIDTH_6_SCALE)];
    wechatLab.centerY = wechatImg.centerY;
    [self label:wechatLab withFont:DEF_FontSize_14 withText:@"微信支付" withTextColor:[UIColor blackColor] withTextAlignment:NSTextAlignmentLeft withView:self.view];
    //微信按钮
    self.wechatBtn = [[UIButton alloc] initWithFrame:CGRectMake(SCREEN_WIDTH - 15/WIDTH_6_SCALE - 16/WIDTH_6_SCALE, 0, 16/WIDTH_6_SCALE, 16/WIDTH_6_SCALE)];
    self.wechatBtn.centerY = wechatLab.centerY;
    [self.view addSubview:self.wechatBtn];
    self.payWay = 1;
    [self.wechatBtn setImage:[UIImage imageNamed:@"paySelect"] forState:UIControlStateNormal];
    //微信行按钮
    UIButton * wechatCoverBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, wechatImg.top, SCREEN_WIDTH, wechatImg.height)];
    [wechatCoverBtn addTarget:self action:@selector(wechatCoverBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [wechatCoverBtn setBackgroundColor:[UIColor clearColor]];
    [self.view addSubview:wechatCoverBtn];
    self.wechatCoverBtn = wechatCoverBtn;
    //支付宝图标
    UIImageView * alipayImg = [[UIImageView alloc] initWithFrame:CGRectMake(20/WIDTH_6_SCALE, 40/WIDTH_6_SCALE + wechatImg.bottom, 28/WIDTH_6_SCALE, 28/WIDTH_6_SCALE)];
    alipayImg.image = [UIImage imageNamed:@"AliPay"];
    [self.view addSubview:alipayImg];
    //支付宝标题
    UILabel * alipayLab = [[UILabel alloc] initWithFrame:CGRectMake(alipayImg.right + 12/WIDTH_6_SCALE, 0, 100/WIDTH_6_SCALE, 15/WIDTH_6_SCALE)];
    alipayLab.centerY = alipayImg.centerY;
    [self label:alipayLab withFont:DEF_FontSize_14 withText:@"支付宝支付" withTextColor:[UIColor blackColor] withTextAlignment:NSTextAlignmentLeft withView:self.view];
    //支付宝按钮
    self.alipayBtn = [[UIButton alloc] initWithFrame:CGRectMake(SCREEN_WIDTH - 15/WIDTH_6_SCALE - 16/WIDTH_6_SCALE, 0, 16/WIDTH_6_SCALE, 16/WIDTH_6_SCALE)];
    self.alipayBtn.centerY = alipayLab.centerY;
    [self.alipayBtn setImage:[UIImage imageNamed:@"payUnselect"] forState:UIControlStateNormal];
    [self.view addSubview:self.alipayBtn];
    //支付宝行按钮
    UIButton * alipayCoverBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, alipayImg.top, SCREEN_WIDTH, alipayImg.height)];
    [alipayCoverBtn addTarget:self action:@selector(alipayCoverBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [alipayCoverBtn setBackgroundColor:[UIColor clearColor]];
    [self.view addSubview:alipayCoverBtn];
    self.alipayCoverBtn = alipayCoverBtn;
    //一米账户图标
    UIImageView * appSelfImg = [[UIImageView alloc] initWithFrame:CGRectMake(wechatImg.left, 40/WIDTH_6_SCALE + alipayImg.bottom, alipayImg.width, alipayImg.height)];
    appSelfImg.image = [UIImage imageNamed:@"appSelf"];
    [self.view addSubview:appSelfImg];
    //一米账户标题
    UILabel * appSelfLab = [[UILabel alloc] initWithFrame:CGRectMake(appSelfImg.right + 12/WIDTH_6_SCALE, 0, 80/WIDTH_6_SCALE, 15/WIDTH_6_SCALE)];
    appSelfLab.centerY = appSelfImg.centerY;
    [self label:appSelfLab withFont:DEF_FontSize_14 withText:@"余额支付" withTextColor:[UIColor blackColor] withTextAlignment:NSTextAlignmentLeft withView:self.view];
    //一米按钮
    self.appSelfBtn = [[UIButton alloc] initWithFrame:CGRectMake(SCREEN_WIDTH - 15/WIDTH_6_SCALE - 16/WIDTH_6_SCALE, 0, 16/WIDTH_6_SCALE, 16/WIDTH_6_SCALE)];
    self.appSelfBtn.centerY = appSelfLab.centerY;
    [self.appSelfBtn setImage:[UIImage imageNamed:@"payUnselect"] forState:UIControlStateNormal];
    [self.view addSubview:self.appSelfBtn];
    //说明
    self.instructionLab = [[UILabel alloc] initWithFrame:CGRectMake(appSelfLab.right, 0, 100/WIDTH_6_SCALE, 15/WIDTH_6_SCALE)];
    self.instructionLab.centerY = appSelfLab.centerY;
    [self label:self.instructionLab withFont:DEF_FontSize_10 withText:@"" withTextColor:getColor(mainRedColor) withTextAlignment:NSTextAlignmentLeft withView:self.view];
    self.instructionLab.hidden = YES;
    //一米覆盖按钮
    UIButton * appSelfCoverBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, appSelfImg.top, SCREEN_WIDTH, appSelfImg.height)];
    [appSelfCoverBtn addTarget:self action:@selector(appSelfCoverBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [appSelfCoverBtn setBackgroundColor:[UIColor clearColor]];
    [self.view addSubview:appSelfCoverBtn];
    self.appSelfCoverBtn = appSelfCoverBtn;
    //确认支付
    UIButton * surePayBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, SCREEN_HEIGHT - NAVI_HEIGHT - BOTTOM_HEIGHT - 49/WIDTH_6_SCALE, SCREEN_WIDTH, 49/WIDTH_6_SCALE)];
    [self button:surePayBtn withBGColor:getColor(@"e92600") withLayerBorderColor:nil withLayerBorderWith:0 withCornerRadius:0 withMasksToBounds:NO withViwe:self.view];
    [surePayBtn setTitle:@"确认支付" forState:UIControlStateNormal];
    [surePayBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [surePayBtn addTarget:self action:@selector(surePayBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    surePayBtn.titleLabel.font = DEF_FontSize_15;
    [self.view addSubview:surePayBtn];
    
    self.wechatCoverBtn.userInteractionEnabled = YES;
    self.alipayCoverBtn.userInteractionEnabled = YES;
    self.appSelfCoverBtn.userInteractionEnabled = YES;
    if ([[UIApplication sharedApplication] canOpenURL:[NSURL  URLWithString:@"weixin://"]]){
        NSLog(@"install--");
    }else{
        NSLog(@"no---");
    }
    
    if ([self isWXAppInstalled]) {
        wechatImg.hidden = NO;
        wechatLab.hidden = NO;
        self.wechatBtn.hidden = NO;
        wechatCoverBtn.hidden = NO;
        alipayImg.hidden = NO;
        alipayLab.hidden = NO;
        self.alipayBtn.hidden = NO;
        alipayCoverBtn.hidden = NO;
        appSelfImg.frame = CGRectMake(wechatImg.left, 40/WIDTH_6_SCALE + alipayImg.bottom, alipayImg.width, alipayImg.height);
        appSelfLab.frame = CGRectMake(appSelfImg.right + 12/WIDTH_6_SCALE, 0, 80/WIDTH_6_SCALE, 15/WIDTH_6_SCALE);
        appSelfLab.centerY = appSelfImg.centerY;
        self.appSelfBtn.frame = CGRectMake(SCREEN_WIDTH - 15/WIDTH_6_SCALE - 16/WIDTH_6_SCALE, 0, 16/WIDTH_6_SCALE, 16/WIDTH_6_SCALE);
        self.appSelfBtn.centerY = appSelfLab.centerY;
        self.instructionLab.frame = CGRectMake(appSelfLab.right, 0, 100/WIDTH_6_SCALE, 15/WIDTH_6_SCALE);
        self.instructionLab.centerY = appSelfLab.centerY;
        self.appSelfCoverBtn.frame = CGRectMake(0, appSelfImg.top, SCREEN_WIDTH, appSelfImg.height);
    }else{
        wechatImg.hidden = YES;
        wechatLab.hidden = YES;
        self.wechatBtn.hidden = YES;
        wechatCoverBtn.hidden = YES;
        alipayImg.hidden = YES;
        alipayLab.hidden = YES;
        self.alipayBtn.hidden = YES;
        alipayCoverBtn.hidden = YES;
        appSelfImg.frame = CGRectMake(20/WIDTH_6_SCALE, self.alertLab.bottom + 20/WIDTH_6_SCALE, 30/WIDTH_6_SCALE, 28/WIDTH_6_SCALE);
        appSelfLab.frame = CGRectMake(wechatImg.right + 12/WIDTH_6_SCALE, 0, 100/WIDTH_6_SCALE, 15/WIDTH_6_SCALE);
        appSelfLab.centerY = appSelfImg.centerY;
        self.appSelfBtn.frame = CGRectMake(SCREEN_WIDTH - 15/WIDTH_6_SCALE - 16/WIDTH_6_SCALE, 0, 16/WIDTH_6_SCALE, 16/WIDTH_6_SCALE);
        self.appSelfBtn.centerY = appSelfLab.centerY;
        self.appSelfCoverBtn.frame = CGRectMake(0, wechatImg.top, SCREEN_WIDTH, wechatImg.height);
        self.instructionLab.frame = CGRectMake(appSelfLab.right, 0, 100/WIDTH_6_SCALE, 15/WIDTH_6_SCALE);
        self.instructionLab.centerY = appSelfLab.centerY;
    }
}
#pragma mark - action
- (void)wechatCoverBtnClick{
    NSLog(@"微信支付");
    self.payWay = 1;
    [self.wechatBtn setImage:[UIImage imageNamed:@"paySelect"] forState:UIControlStateNormal];
    [self.alipayBtn setImage:[UIImage imageNamed:@"payUnselect"] forState:UIControlStateNormal];
    [self.appSelfBtn setImage:[UIImage imageNamed:@"payUnselect"] forState:UIControlStateNormal];
}
- (void)alipayCoverBtnClick{
    NSLog(@"支付宝支付");
    self.payWay = 2;
    [self.alipayBtn setImage:[UIImage imageNamed:@"paySelect"] forState:UIControlStateNormal];
    [self.wechatBtn setImage:[UIImage imageNamed:@"payUnselect"] forState:UIControlStateNormal];
    [self.appSelfBtn setImage:[UIImage imageNamed:@"payUnselect"] forState:UIControlStateNormal];
}
- (void)appSelfCoverBtnClick{
    NSLog(@"一米支付");
    self.payWay = 3;
    [self.alipayBtn setImage:[UIImage imageNamed:@"payUnselect"] forState:UIControlStateNormal];
    [self.wechatBtn setImage:[UIImage imageNamed:@"payUnselect"] forState:UIControlStateNormal];
    [self.appSelfBtn setImage:[UIImage imageNamed:@"paySelect"] forState:UIControlStateNormal];
}
- (void)surePayBtnClick:(UIButton *)sender{
    NSLog(@"确认支付");
    if (self.payWay == 1) {
        NSLog(@"微信支付");
        if ([self isWXAppInstalled]) {
            [self weChatPay];
        }else{
            ShowMessage(@"请安装微信");
            return;
        }
    }
    if (self.payWay == 2){
        NSLog(@"支付宝支付");
        [self aliPay];
    }
    if (self.payWay == 3) {
        NSLog(@"一米支付");
        [self appSelfAccountPay];
    }
}
- (void)ifLogin{
    __weak typeof (self)weakSelf = self;
    WeChatLoginViewController * vc = [[WeChatLoginViewController alloc] init];
    UINavigationController* navi = [[UINavigationController alloc] initWithRootViewController:vc];
    vc.backHomePageBlock = ^{
        [vc dismissViewControllerAnimated:YES completion:nil];
        NSArray *vcsArray = [self.navigationController viewControllers];
        NSInteger vcCount = vcsArray.count;
        weakSelf.rootVC = vcsArray[0];
        if ([self.rootVC isKindOfClass:[MallViewController class]]) {
            //网络接口，从酒店和其他进
            [weakSelf.navigationController popToRootViewControllerAnimated:YES];
        }else{
            [weakSelf.tabBarController setSelectedIndex:0];
            [weakSelf.navigationController popToRootViewControllerAnimated:YES];
        }
    };
    [self presentViewController:navi animated:YES completion:nil];
}
#pragma mark - 支付宝支付
- (void)alipayWay:(NSString * )codeString{
    // NOTE: 调用支付结果开始支付
    [[AlipaySDK defaultService] payOrder:codeString fromScheme:@"ShengXuntechnologyMeterMart" callback:^(NSDictionary *resultDic) {
        if ([resultDic[@"resultStatus"] isEqualToString:@"6001"]) {
            ShowMessage(@"支付失败！");
        }
        if ([resultDic[@"resultStatus"] isEqualToString:@"9000"]) {
            [[NSNotificationCenter defaultCenter]postNotificationName:@"payStatus" object:nil userInfo:@{@"payStatus":@"1"}];
            [self.view makeToast:@"支付成功!" duration:1 position:CSToastPositionCenter title:nil image:nil style:nil completion:^(BOOL didTap) {
                //返回到指定的控制器，要保证前面有入栈。
                int index = (int)[[self.navigationController viewControllers]indexOfObject:self];
                if (index>2) {
                    [self.navigationController popToViewController:[self.navigationController.viewControllers objectAtIndex:(index-2)] animated:YES];
                }else{
                    [self.navigationController popToRootViewControllerAnimated:YES];
                }
            }];
        }
    }];
}
//支付宝支付成功
- (void)aliPaySucceed:(NSNotification *)notify{
    [[NSNotificationCenter defaultCenter]postNotificationName:@"payStatus" object:nil userInfo:@{@"payStatus":@"1"}];
    
    int64_t delayInSeconds = 1.0; // 延迟的时间
    /*
     *  delta:
     *
     *  @parameter 1.时间参照，从此刻开始计时
     *  @parameter 2.延时多久，此处为秒级，还有纳秒等: 10ull * NSEC_PER_MSEC
     */
    ShowMessage(@"支付成功");
    __weak typeof(self)weakSelf = self;
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [weakSelf.tabBarController setSelectedIndex:2];
        [weakSelf.navigationController popToRootViewControllerAnimated:YES];
    });
}
- (void)payStatus:(NSNotification *)notification{
    NSDictionary * dic = notification.userInfo;
    NSLog(@"支付状态：%@", dic[@"payStatus"]);
}
//支付宝支付失败
- (void)aliPayFailed:(NSNotification *)notify{
    ShowMessage(@"支付失败");
}
//微信支付（成功之后的回调）
- (void)weixinPaySuccess:(NSNotification *)notification{
    NSDictionary * dic = notification.userInfo;
    NSString * mark = dic[@"key"];
    NSLog(@"%@", mark);
    
    [[NSNotificationCenter defaultCenter]postNotificationName:@"payStatus" object:nil userInfo:@{@"payStatus":@"1"}];
    
    int64_t delayInSeconds = 1.0; // 延迟的时间
    /*
     *  delta:
     *
     *  @parameter 1.时间参照，从此刻开始计时
     *  @parameter 2.延时多久，此处为秒级，还有纳秒等: 10ull * NSEC_PER_MSEC
     */
    ShowMessage(@"支付成功");
    __weak typeof(self)weakSelf = self;
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [weakSelf.tabBarController setSelectedIndex:2];
        [weakSelf.navigationController popToRootViewControllerAnimated:YES];
    });
}
//调起微信支付功能
- (void)weiXinpay:(NSDictionary *)dic{
    PayReq *request = [[PayReq alloc]init];
    request.partnerId = dic[@"partnerid"];
    request.timeStamp = [dic[@"timestamp"] intValue];
    request.sign = dic[@"sign"];
    request.prepayId = dic[@"prepayid"];
    request.nonceStr = dic[@"noncestr"];
    request.package = dic[@"package"];
    [WXApi sendReq:request];
}
//是否安装微信
- (BOOL)isWXAppInstalled
{
    return [WXApi isWXAppInstalled];
}
- (void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"payStatus" object:nil];
}
@end
